package com.voxel.sense.infomsg.module.map.monitor.traceRecord;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.IDialog;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.response.TraceListEntity;

public class TraceActivity extends BViewActivity<TraceContract.Presenter> implements TraceContract.View {


    @BindView(R.id.bt_record)
    Button bt_record;
    @BindView(R.id.map_view)
    MapView map_view; //地图
    @BindView(R.id.titlebar)
    TextTitleBar titlebar; //地图

    private AMap aMap;//地图操作的实例
    private PolylineOptions mPolyoptions;//轨迹路线实例
    private MyLocationStyle mMyLocationStyle;

    private boolean record_flag = false;
    private List<File> mFiles;
    private OptionsPickerView mPvCustomOptions;
    private double mLatitude;
    private double mLongitude;


    public static void show(Context context, double latitude, double longitude) {
        Bundle bundle = new Bundle();
        bundle.putDouble(IntentConstants.LATITUDE, latitude);
        bundle.putDouble(IntentConstants.LONGITUDE, longitude);

        Intent i = new Intent(context, TraceActivity.class);
        i.putExtras(bundle);
        context.startActivity(i);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_trace;
    }

    @Override
    protected TraceContract.Presenter initPresenter() {
        return new TracePresenter(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map_view.onCreate(savedInstanceState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map_view.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mLocationReceiver != null)
//            unregisterReceiver(mLocationReceiver); asset
        map_view.onDestroy();
    }


    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            mLatitude = bundle.getDouble(IntentConstants.LATITUDE);
            mLongitude = bundle.getDouble(IntentConstants.LONGITUDE);
        }
        return super.initArgs(bundle);
    }

    @Override
    protected void initData() {
        super.initData();
        mPolyoptions = new PolylineOptions();
        if (aMap == null) {
            aMap = map_view.getMap();
            aMap.moveCamera(CameraUpdateFactory.
                    changeLatLng(new LatLng(mLatitude,mLongitude)));
        }
        setMapConfig();


        titlebar.setRightTextAndLis("记录轨迹", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = record_flag == true ? "停止记录您的行程" : "开始记录您的行程";

                IDialog.getInstance().showChooseDialog(TraceActivity.this, "", msg, new DialogCallBack() {
                    @Override
                    public void onClick(int what) {
                        if (what == IDialog.YES) {
                            if (record_flag) {
                                record_flag = false;
                                titlebar.setRightText("开启定位");

//                    sendBroadcast(Utils.getCloseBrodecastIntent());
                                mPresenter.doStopRecord();
                                //unregisterReceiver(mLocationReceiver);
                            } else {
                                mPresenter.doRecordTrace();
                                //注册广播
                                record_flag = true;
                                titlebar.setRightText("停止定位");
//                                mScreenListener.stopScreenReceiverListener();
                            }
                        }
                    }
                });
            }
        });
    }

    private void setMapConfig() {
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);

        mMyLocationStyle = new MyLocationStyle();
        //蓝点定位一次
        mMyLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        mMyLocationStyle.radiusFillColor(android.R.color.transparent);
        mMyLocationStyle.strokeColor(android.R.color.transparent);
        aMap.setMyLocationStyle(mMyLocationStyle);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        //设置最小缩放的等级数值
        aMap.setMinZoomLevel(Constants.MAP_MIN_ZOOM_LEVEL);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constants.MAP_DEFAULT_ZOOM_LEVEL));
//        aMap.addPolyline(mPolyoptions);
    }

    @Override
    protected void initEven() {
        super.initEven();
        bt_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = record_flag == true ? "停止记录您的行程" : "开始记录您的行程";

                IDialog.getInstance().showChooseDialog(TraceActivity.this, "", msg, new DialogCallBack() {
                    @Override
                    public void onClick(int what) {
                        if (what == IDialog.YES) {
                            if (record_flag) {
                                record_flag = false;
                                bt_record.setText("开启定位");

//                    sendBroadcast(Utils.getCloseBrodecastIntent());
                                mPresenter.doStopRecord();
                                //unregisterReceiver(mLocationReceiver);
                            } else {
                                mPresenter.doRecordTrace();
                                //注册广播
                                record_flag = true;
                                bt_record.setText("停止定位");

//                    IntentFilter intentFilter = new IntentFilter();
//                    intentFilter.addAction(Constants.LOCATION_RECEIVEER_ACTION);
                                //registerReceiver(mLocationReceiver, intentFilter);
                            }
                        }
                    }
                });

            }
        });

        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                /**
                 * 高精度定位模式下会采用GPS定位混合网络定位的方式。开启持续高精度定位，
                 * 如果此时GPS模块没有正常工作是无法正常返回角度、速度、海拔数据的，但网络定位生效，可以有效的返回经纬度信息。
                 * 角度、速度、海拔数据返回负数说明GPS状态现在是不太好的，无法准确计算结果。如果返回0意味着GPS状态可用，但设备没有移动。
                 * 仅设备定位模式只能在室外环境生效，这是由于GPS模块只有在开阔场所才可以有效的连接卫星计算位置，这点需要注意。
                 */
                float spped = location.getSpeed();

                if (spped != 0) {
                    ToastUtil.showToastShort(Factory.app(), "getSpeed" + spped);
                    L.d("speedAccuracyMetersPerSecond:" + spped);
                } else {
                    L.d("没有速度:" + spped + "---getBearing:" + location.getBearing() + "--" + location.getAccuracy());
                }

                double latitude = location.getLatitude();
                double longgitude = location.getLongitude();
                //先判断是否定位成功,且判断速度若为0，则设备没有移动，无需改变位置
//                if ((latitude == 0 && longgitude == 0) || spped == 0)
                if ((latitude == 0 && longgitude == 0))
                    return;
//                L.d("LATITUDE:" + latitude + "----longgitude" + longgitude);
//                mMyLocationStyle.anchor((float) latitude,(float) longgitude);
//                aMap.setMyLocationStyle(mMyLocationStyle);
                mPresenter.doUpMyLocaton(location);
            }
        });

        View viewById = findViewById(R.id.bt_history);
        initCustomOptionPicker();
        findViewById(R.id.bt_history).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> strings = initTracedatas();
                showOption(strings, "没有数据");
            }
        });
    }

    /**
     * 弹出选择器
     */
    private void showOption(List<String> list, String msg) {
        if (list != null && list.size() > 0) {
            mPvCustomOptions.setPicker(list);
            mPvCustomOptions.show();
        } else {
            ToastUtil.showToastShort(Factory.app(), msg);
        }
    }

    //条件选择器初始化，自定义布局
    private OptionsPickerView initCustomOptionPicker() {
        //初始化布局
//点击完成
//点击取消
//                .isDialog(true)
        mPvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                File file = mFiles.get(options1);

                ObjectInputStream ois = null;
                try {
                    TraceListEntity entity = null;
                    ArrayList<LatLng> latLngs = new ArrayList<>();
                    ois = new ObjectInputStream(new FileInputStream(file));
                    entity = (TraceListEntity) ois.readObject();
                    List<TraceListEntity.Coordinates> coordinates = entity.coordinates;
                    for (TraceListEntity.Coordinates b : coordinates) {
                        latLngs.add(new LatLng(b.latitude, b.longitude));
                    }
                    L.d("---coordinates:" + coordinates.size());
                    ois.close();
                    PolylineOptions options = new PolylineOptions();
                    options.width(10);
                    options.color(Color.GREEN);
                    options.addAll(latLngs);
                    Polyline polyline = aMap.addPolyline(options);
//
//                     mOptimizeLat = tool.pathOptimize(latLngs);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {//初始化布局
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                        //点击完成
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.returnData();
                                mPvCustomOptions.dismiss();
                            }
                        });
                        //点击取消
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.dismiss();
                            }
                        });
                    }
                })
                //                .isDialog(true)
                .build();

        return mPvCustomOptions;
    }

    @Override
    public void onDrawLine(PolylineOptions options) {
        aMap.addPolyline(options);
    }


    private BroadcastReceiver mLocationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action) && Constants.LOCATION_RECEIVEER_ACTION.equals(action)) {
                double latitude = intent.getDoubleExtra(IntentConstants.LATITUDE, 0);
                double longgitude = intent.getDoubleExtra(IntentConstants.LONGITUDE, 0);
//                mMyLocationStyle.anchor((float) latitude,(float) longgitude);
//                aMap.setMyLocationStyle(mMyLocationStyle);

//                mPresenter.doUpMyLocaton(latitude, longgitude);
            }
        }
    };

    @Override
    public void onBackPressed() {
        if (record_flag) {
            IDialog.getInstance().showChooseDialog(this, "", "正在记录移动轨迹，是否要停止记录", new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (what == IDialog.YES) {
                        TraceActivity.super.onBackPressed();
                    }
                }
            });
        } else {
            super.onBackPressed();
        }
    }





    private List<String> initTracedatas() {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        File dir = new File(externalStorageDirectory, "/TraceRecord");
        mFiles = FileUtils.listFilesInDir(dir);
        L.d("traceDir:" + dir.getAbsolutePath());
        L.d("traceDir:" + dir.getPath());
        ArrayList<String> arrayList = new ArrayList();
        if (mFiles != null && mFiles.size() > 0) {
            arrayList = new ArrayList();
            for (File f : mFiles) {
                arrayList.add(f.getName());
            }
        }
        return arrayList;
    }
}
